import {
  Injectable,
  NotFoundException,
  ForbiddenException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { PostEntity } from './entities/post.entity';
import { CreatePostDto } from './dto/create-post.dto';
import { ScenicSpotEntity } from 'src/scenic-spot/entities/scenic-spot.entity';
import { CommentService } from '../comment/comment.service';
import { UserFavoriteEntity } from 'src/user-favorite/entities/user-favorite.entity';
import { UserLikeEntity } from 'src/user-like/entities/user-like.entity';
import { UpdatePostDto } from './dto/update-post.dto';
import { ImageEntity } from 'src/image/entities/image.entity';
import { join } from 'path';
import { readFileSync, unlinkSync } from 'fs';
import sizeOf from 'image-size';
import { OssService } from 'src/common/oss/oss.service';
@Injectable()
export class PostService {
  constructor(
     private readonly ossService: OssService,
    @InjectRepository(PostEntity)
    private postRepo: Repository<PostEntity>,
    @InjectRepository(ScenicSpotEntity)
    private spotRepo: Repository<ScenicSpotEntity>,
    private commentSvc: CommentService,
    @InjectRepository(UserLikeEntity)
    private likeRepo: Repository<UserLikeEntity>,
    @InjectRepository(UserFavoriteEntity)
    private favRepo: Repository<UserFavoriteEntity>,
    @InjectRepository(ImageEntity)
    private imageRepo: Repository<ImageEntity>,
  ) {}

  async create(dto: CreatePostDto, authorId: number): Promise<PostEntity> {
    const spot = await this.spotRepo.findOne({
      where: { id: dto.scenicSpotId },
    });
    if (!spot) throw new NotFoundException('景区不存在');

    const post = this.postRepo.create({
      ...dto,
      scenicSpot: spot,
      author: { id: authorId } as any,
    });
    return this.postRepo.save(post);
  }

  

 async createWithImage(
    file: Express.Multer.File,
    body: any,
    authorId: number,
  ): Promise<PostEntity> {
    try {
      const spot = await this.spotRepo.findOne({ where: { id: +body.scenicSpotId } });
      if (!spot) throw new NotFoundException('景区不存在');

      // const filePath = join(process.cwd(), 'uploads', file.filename);
      const filePath = file.path; // Multer 自带路径

      console.log('准备删除路径：', filePath); // 打印路径看看是否对
      const buffer = readFileSync(filePath); // 读取图片内容
      const dimensions = sizeOf(buffer); // 解析宽高

      const ossUrl = await this.ossService.uploadBuffer(buffer, file.filename); // 上传到 OSS
    try {
  unlinkSync(filePath);
  console.log('文件已删除：', filePath);
} catch (err) {
  console.error('删除失败：', err);
}
      const image = await this.imageRepo.save({
        width: dimensions.width,
        height: dimensions.height,
        src: ossUrl,
      });

      const post = this.postRepo.create({
        scenicSpot: spot,
        address: body.address,
        addressDescription: body.addressDescription,
        idea: body.idea,
        environment: body.environment,
        shotTime: new Date(body.shotTime),
        image,
        author: { id: authorId } as any,
      });

      return this.postRepo.save(post);
    } catch (error) {
      console.error('创建帖子出错:', error);
      throw error;
    }
  }
  async findById(id: number): Promise<any> {
    const post = await this.postRepo.findOne({
      where: { id },
      relations: ['author', 'scenicSpot'],
    });

    if (!post) throw new NotFoundException('帖子未找到');

    const comments = await this.commentSvc.findByPost(id);
    return { post, comments };
  }

  async findAll(): Promise<PostEntity[]> {
    return this.postRepo.find({ relations: ['author', 'scenicSpot'] });
  }

  async findAllByPopularity(): Promise<PostEntity[]> {
    return this.postRepo.find({
      order: {
        likeCount: 'DESC',
        favoriteCount: 'DESC',
        commentCount: 'DESC',
      },
    });
  }

  async findByScenicSpot(spotId: number): Promise<PostEntity[]> {
    return this.postRepo.find({
      where: { scenicSpot: { id: spotId } },
      relations: ['author'],
    });
  }

  async update(postId: number, dto: UpdatePostDto, authorId: number) {
    const post = await this.postRepo.findOne({
      where: { id: postId },
      relations: ['author'],
    });
    if (!post) throw new NotFoundException('帖子不存在');
    if (post.author.id !== authorId)
      throw new ForbiddenException('无权限编辑该帖子');

    Object.assign(post, dto);
    return this.postRepo.save(post);
  }

  async remove(id: number) {
    const res = await this.postRepo.delete(id);
    if (res.affected === 0) throw new NotFoundException('帖子不存在或已删除');
    return { message: '删除成功' };
  }

  async like(postId: number, userId: number) {
    const exist = await this.likeRepo.findOne({
      where: { post: { id: postId }, user: { id: userId } },
    });

    if (exist) throw new ForbiddenException('已点赞');
    await this.likeRepo.save({
      post: { id: postId } as any,
      user: { id: userId } as any,
    });
    await this.postRepo.increment({ id: postId }, 'likeCount', 1);
    return { message: '点赞成功' };
  }

  async favorite(postId: number, userId: number) {
    const exist = await this.favRepo.findOne({
      where: { post: { id: postId }, user: { id: userId } },
    });

    if (exist) throw new ForbiddenException('已收藏');
    await this.favRepo.save({
      post: { id: postId } as any,
      user: { id: userId } as any,
    });
    await this.postRepo.increment({ id: postId }, 'favoriteCount', 1);
    return { message: '收藏成功' };
  }
  async findPaginated(page:number,pageSize:number){
    const [list,total]=await this.postRepo.findAndCount({
      skip:(page-1)*pageSize,
      take:pageSize,
     order: { createdAt: 'DESC' }, // 可选，按时间倒序
    relations: ['author', 'scenicSpot', 'image'], // 可选，填充关联信息

    })
     return {
    total,
    list,
  };
  }
}